<?php
class BaseAction extends Action {
	public $wxid ,$browser,$muser,$puls;
    public $token , $mptoken, $mid, $mtoken, $appkey, $apptoken,$member,$mpaccount;
    public $FromUserName , $ToUserName, $MsgType, $Content , $Location_X, $Location_Y, $Event , $Latitude, $Longitude, $Precision, $Scale, $CreateTime, $Label, $PicUrl, $FuncFlag, $MsgId, $Title, $Url, $Description, $EventKey,$Recognition;
    public $textdata,$imagedata,$locdata,$linkdata,$eventdata,$wxpost,$voicedata;
    public $mType = "text";
    public $volist;
	function _initialize() {
		$x = $_GET['x'];
    	if ($x) {
    		$this->mid = $x;
        	$echoStr = $_GET["echostr"];
    		if ($this->checkSignature()) {
                echo $echoStr;
                $this->wxapi();
                exit();
    		}
            if (I('t')) {
                $this->wxapi();
            }
    		exit();
    	}
        unset($map);
        $Apps = M('Apps');
        $map['mid'] = 1;
        $apps = $Apps->where($map)->find();
        $this->assign('apps',$apps);
	}

	public function initindex()
    {
    	$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
		if ($postObj) {
            $this->FromUserName = trim($postObj->FromUserName);
            $this->ToUserName = trim($postObj->ToUserName);
            $this->MsgType = trim($postObj->MsgType);
            $this->Content = trim($postObj->Content);
            $this->Location_X = trim($postObj->Location_X);
            $this->Location_Y = trim($postObj->Location_Y);
            $this->Event = trim($postObj->Event);
            $this->Latitude = trim($postObj->Latitude);
            $this->Longitude = trim($postObj->Longitude);
            $this->Precision = trim($postObj->Precision);
            $this->Scale = trim($postObj->Scale);
            $this->CreateTime = trim($postObj->CreateTime);
            $this->Label = trim($postObj->Label);
            $this->PicUrl = trim($postObj->PicUrl);
            $this->FuncFlag = trim($postObj->FuncFlag);
            $this->MsgId = trim($postObj->MsgId);
            $this->Url = trim($postObj->Url);
            $this->EventKey = trim($postObj->EventKey);
            $this->Description = trim($postObj->Description);
            $this->Recognition = trim($postObj->Recognition);
        }else{
            $this->FromUserName = $this->_param('FromUserName');
            $this->ToUserName = $this->_param('ToUserName');
            $this->MsgType = $this->_param('MsgType');
            $this->Content = $this->_param('Content');
            $this->Location_X = $this->_param('Location_X');
            $this->Location_Y = $this->_param('Location_Y');
            $this->Event = $this->_param('Event');
            $this->Latitude = $this->_param('Latitude');
            $this->Longitude = $this->_param('Longitude');
            $this->Precision = $this->_param('Precision');
            $this->Scale = $this->_param('Scale');
            $this->CreateTime = $this->_param('CreateTime');
            $this->Label = $this->_param('Label');
            $this->PicUrl = $this->_param('PicUrl');
            $this->FuncFlag = $this->_param('FuncFlag');
            $this->MsgId = $this->_param('MsgId');
            $this->Url = $this->_param('Url');
            $this->EventKey = $this->_param('EventKey');
            $this->Description = $this->_param('Description');
            $this->Recognition = $this->_param('Recognition');
        }
        $this->volist =  array();

        if ($this->_param('t')) {
            $this->Content = $this->_param('t');
            $this->MsgType = "text";
        }

        $this->mType =  $this->_param('mType');
        if (!$this->mType) {
            $this->mType = "text";
        }

        $this->q =  $this->_param('q');
        $this->q = trim($this->q);
        $this->assign('time', time());
        $this->assign('FromUserName', $this->FromUserName);
        $this->assign('ToUserName', $this->ToUserName);

        //菜单事件
        if ($this->MsgType == "event" && strtolower($this->Event) == "click") {
            $mm['key'] = $this->EventKey;
            $mm['mid'] = $this->mid;
            $Wxmenu = M('Wxmenu');
            $wx = $Wxmenu->where($mm)->find();
            // F(time(),$wx);
            if ($wx['keyword']) {
                $this->Content = $wx['keyword'];
            }
            
        }

        //Recognition 语音输入
        if ($this->MsgType == 'voice') {
            if ($this->Recognition) {
                $this->Content = substr($this->Recognition,0,-3);
            }
        }

        $basedata['mid'] = $this->mid;
        $basedata['FromUserName'] = $this->FromUserName;
        $basedata['ToUserName'] = $this->ToUserName;
        $basedata['CreateTime'] = $this->CreateTime;
        $basedata['MsgType'] = $this->MsgType;
        $basedata['MsgId'] = $this->MsgId;
        $basedata['keyword'] = $this->Content;
        $basedata['keywords'] = $this->Content;
        $basedata['Content'] = $this->Content;


        $this->wxpost = $basedata;
        $this->textdata = $basedata;
        $this->textdata['Content'] = $this->Content;

        $this->imagedata = $basedata;
        $this->imagedata['PicUrl'] = $this->PicUrl;
        $this->wxpost['PicUrl'] = $this->PicUrl;

        $this->locdata = $basedata;
        $this->locdata['Location_X'] = $this->Location_X;
        $this->locdata['Location_Y'] = $this->Location_Y;
        $this->locdata['Scale'] = $this->Scale;
        $this->locdata['Label'] = $this->Label;

        $this->wxpost['Location_X'] = $this->Location_X;
        $this->wxpost['Location_Y'] = $this->Location_Y;
        $this->wxpost['Scale'] = $this->Scale;
        $this->wxpost['Label'] = $this->Label;

        $this->wxpost['wxaccount'] = $this->ToUserName;

        $this->linkdata = $basedata;
        $this->linkdata['Title'] = $this->Title;
        $this->linkdata['Description'] = $this->Description;
        $this->linkdata['Url'] = $this->Url;

        $this->wxpost['Title'] = $this->Title;
        $this->wxpost['Description'] = $this->Description;
        $this->wxpost['Url'] = $this->Url;
        
        $this->eventdata = $basedata;
        $this->eventdata['Event'] = $this->Event;
        $this->eventdata['EventKey'] = $this->EventKey;

        $this->wxpost['Event'] = $this->Event;
        $this->wxpost['EventKey'] = $this->EventKey;

        //Recognition 语音输入
        $this->wxpost['Recognition'] = $this->Recognition;


        ///首次登陆的用户会自动注册
        unset($map);
        $map['wxid'] = $this->FromUserName;
        $map['mid'] = $this->mid;
        $Muser = M("Muser");
        $muser = $Muser->where($map)->find();
        if (!$muser) {
            $Muser->add($map);
            $muser = $Muser->where($map)->find();
        }
        $this->muser = $muser;
        ///首次登陆的用户会自动注册


    }
    ///微网站的文章查询
    public function infos(){
        $map['mid'] = $this->mid;
        $_string = " FIND_IN_SET ('$this->Content',keyword) ";
        $map['_string'] = " FIND_IN_SET ('$this->Content',keyword) ";
        $map['keyword'] = array('neq',' ');
        $Info = D('Info');
        $toplist = array();
        $top2_arr = $Info->_list_($map);
        if ($top2_arr['volist']) {
            $toplist = array_merge($toplist,$top2_arr['volist']);
        }
        return $toplist;
    }

    ///微网站的分类查询
    public function itype(){
        $map['mid'] = $this->mid;
        $map['keyword'] = array('neq',' ');
        $map['_string'] = " FIND_IN_SET ('$this->Content',keyword) ";
        $InfoType = D('InfoType');
        $toplist = array();
        $top2_arr = $InfoType->_list_($map);
        if ($top2_arr['volist']) {
            $toplist = array_merge($toplist,$top2_arr['volist']);
        }
        return $toplist;
    }

    public function topnews1()
    {
        $toplist = array();
        $top1_arr = array();
        $top2_arr = array();
        $News = D('News');
        $News->muser = $this->muser;
        $News->member = $this->member;

        $map['mid'] = $this->mid;
        $map['top'] = array('between','1,10');
        $_string = " FIND_IN_SET ('$this->Content',keywords) ";
        $map['_string'] = $_string;
        // $top2_arr = $News->where($map)->order('top,id desc')->limit(5)->select();
        $top2_arr = $News->top($map);
        if ($top2_arr) {
            $toplist = array_merge($toplist,$top2_arr);
        }
        return $toplist;
    }
    public function topnews2()
    {
        $toplist = array();
        $top1_arr = array();
        $top2_arr = array();
        $News = D('News');
        $News->muser = $this->muser;
        $News->member = $this->member;

        $map['top'] = array('between','11,20');
        $map['mid'] = $this->mid;        
        // $top1_arr = $News->where($map)->order('top,id desc')->limit(5)->select();
        $top1_arr = $News->top($map);
        if ($top1_arr) {
            $toplist = array_merge($toplist,$top1_arr);
        }

        return $toplist;
    }

    //局部置底回复
    public function bottomreply1()
    {
        $toplist = array();
        $top1_arr = array();
        $top2_arr = array();
        $News = D('News');
        $News->muser = $this->muser;
        $News->member = $this->member;

        $map['top'] = array('between','21,30');
        $map['mid'] = $this->mid;
        $_string = " FIND_IN_SET ('$this->Content',keywords) ";
        $map['_string'] = $_string;
        $top1_arr = $News->top($map);
        if ($top1_arr) {
            $toplist = array_merge($toplist,$top1_arr);
        }

        return $toplist;
    }

    //全局置底回复
    public function bottomreply2()
    {
        $toplist = array();
        $top1_arr = array();
        $top2_arr = array();
        $News = D('News');
        $News->muser = $this->muser;
        $News->member = $this->member;

        $map['top'] = array('between','31,40');
        $map['mid'] = $this->mid;
        $top1_arr = $News->top($map);
        if ($top1_arr) {
            $toplist = array_merge($toplist,$top1_arr);
        }

        return $toplist;
    }


    //////词库匹配
    //关键词匹配调整 完全匹配 例如 keyword = "火锅"
    function matchTextInfo1(){
        if (!$this->Content) return;
        $Textinfo = M('Textinfo');
        $map['mid'] = $this->mid;
        $map['keywords'] = $this->Content;
        $vos = $Textinfo->where($map)->order('id desc')->find();
        // print_r($vos);
        // print_r($Info->getlastSql());
        
        return $vos;
    }
    //关键词匹配调整 包含匹配 例如 keyword = "火锅,药店"
    function matchTextInfo2(){
        if (!$this->Content) return;
        $Textinfo = M('Textinfo');
        $map['mid'] = $this->mid;
        $_string = " FIND_IN_SET ('$this->Content',keywords) ";
        $map['_string'] = $_string;
        $vos = $Textinfo->where($map)->order('id desc')->find();
        // print_r($vos);
        // print_r($Info->getlastSql());
        // exit();
        return $vos;
    }

    //词库匹配
    function matchTextInfo3(){
        if (!$this->Content) return;
        $Textinfo = M('Textinfo');
        $map['mid'] = $this->mid;
        $ret = getsegment($this->Content);
        $keyarr = array();
        foreach ($ret as $key) {
            if (strlen($key) > 3) {
                $keyarr[] = $key;
            }
        }
        $keyarr = array_flip(array_flip($keyarr));
        $_string = "";
        for ($i=0; $i < count($keyarr); $i++) { 
            if ($i > 8) break;
            if ($keyarr[$i] == "") continue;
            if ($_string) $_string .= " or ";
            $_string .= " FIND_IN_SET ('$keyarr[$i]',keywords) ";
        }

        if ( $_string) 
            $map['_string'] = $_string;
        if (!$_string) return;
        $vos = $Textinfo->where($map)->order('id desc')->find();
        // print_r($Sentence->getlastSql());
        // exit();
        return $vos;
    }

    //关键词匹配调整 模糊匹配 例如 keyword like "%火锅%"
    function matchTextInfo4(){
        if (!$this->Content) return;
        $Textinfo = M('Textinfo');
        $map['mid'] = $this->mid;
        if (mb_strlen($this->Content) > 8) {
            $map['keywords'] = array('like',"%".$this->Content."%");
            $vos = $Textinfo->where($map)->order('id desc')->find();
            return $vos;
        }
        
    }

    //////词库匹配



    


    /////回复匹配
    //关键词匹配调整 完全匹配 例如 keyword = "火锅"
    function matchNews1(){
        if (!$this->Content) return;
        $News = D('News');
        $News->muser = $this->muser;
        $News->member = $this->member;
        $map['top'] = 0;
        $map['mid'] = $this->mid;
        $map['keywords'] = $this->Content;
        $vos = $News->_list($map);
        // $vos = $News->where($map)->order('id desc')->limit(9)->select();
        // print_r($News->getlastSql());
        // exit();
        return $vos;
    }
    //关键词匹配调整 包含匹配 例如 keyword = "火锅,药店"
    function matchNews2(){
        if (!$this->Content) return;
        $News = D('News');
        $News->muser = $this->muser;
        $News->member = $this->member;
        $map['top'] = 0;
        $map['mid'] = $this->mid;
        $_string = " FIND_IN_SET ('$this->Content',keywords) ";
        $map['_string'] = $_string;
        // $vos = $News->where($map)->order('id desc')->limit(9)->select();
        $vos = $News->_list($map);
        // print_r($vos);
        // print_r($News->getlastSql());
        // exit();
        return $vos;
    }

    //词库匹配
    function matchNews3(){
        if (!$this->Content) return;
        $News = D('News');
        $News->muser = $this->muser;
        $News->member = $this->member;
        $map['top'] = 0;
        $map['mid'] = $this->mid;
        $ret = getsegment($this->Content);
        $keyarr = array();
        foreach ($ret as $key) {
            if (strlen($key) > 3) {
                $keyarr[] = $key;
            }
        }
        $keyarr = array_flip(array_flip($keyarr));
        $_string = "";
        for ($i=0; $i < count($keyarr); $i++) { 
            if ($i > 8) break;
            if ($keyarr[$i] == "") continue;
            if ($_string) $_string .= " or ";
            $_string .= " FIND_IN_SET ('$keyarr[$i]',keywords) ";
        }

        if ( $_string) 
            $map['_string'] = $_string;
        if (!$_string) return;
        // $vos = $News->where($map)->order('id desc')->limit(9)->select();
        $vos = $News->_list($map);
        // print_r($Sentence->getlastSql());
        // exit();
        return $vos;
    }

    //关键词匹配调整 模糊匹配 例如 keyword like "%火锅%"
    function matchNews4(){
        $News = D('News');
        $News->muser = $this->muser;
        $News->member = $this->member;
        $map['top'] = 0;
        $map['mid'] = $this->mid;
        if (mb_strlen($this->Content) > 8) {
            $map['keywords'] = array('like',"%".$this->Content."%");
            $vos = $News->_list($map);
            // $vos = $News->where($map)->order('id desc')->limit(9)->select();
            return $vos;
        }
        
    }

    public function Wxmsgadd($data)
    {
        if ($data['MsgId'] == 0) return;
        if ($data['plusid'] == 0) return;
        if (I('t')) return;
        $Wxmsg = M('Wxmsg');
        $this->wxpost['year'] = date('Y', $this->CreateTime);
        $this->wxpost['moth'] = date('m', $this->CreateTime);
        $this->wxpost['day'] = date('d', $this->CreateTime);
        $this->wxpost['muid'] = $this->muser['id'];
        $Wxmsg->add($this->wxpost);
    }

    public function respon($tpl)
    {
        if (I('t') == '' && $this->FromUserName == "") {;
            return;
        }
        $tvlist = json_encode($this->volist);
        $liststr = replacewx($tvlist,$this->wxpost);
        $this->msg = replacewx($this->msg,$this->wxpost);
        
        $this->volist = json_decode($liststr,true);
        // $vlist = json_decode($liststr,true);

        $this->assign('volist',$this->volist);
        $this->assign('count',count($this->volist));


        $this->assign('HTTP_USER_AGENT',$_SERVER['HTTP_USER_AGENT']);

        $this->assign('msg',$this->msg);
        $this->display(trim($tpl));
    }

    ///插件
    public function searchPlus()
    {
        $Plus = D('Plus');
        $map['mid'] = $this->mid;
        $myplus = $Plus->where($map)->select();
        $plusvolist =  array();
        foreach ($myplus as $k) {
            $$k['code'] = A('Plus/'.ucfirst($k['code']));
            $plus = $$k['code'];
            $plus->wxpost = $this->wxpost;
            $plus->muser = $this->muser;
            $plus->member = $this->member;
            $plus->myPlus = unserialize($k['opt']);
            $plus->myPlusFull = $k;
            $retMsg = $plus->getMsg();
            if ($retMsg['msgType'] == 'text') {
                $this->msg = $retMsg['msg'];
                $this->respon('text');
                exit();
            }elseif ($retMsg['msgType'] == 'news') {
                $this->volist = array_merge($retMsg['volist'],$this->volist);
                $plusvolist = array_merge($retMsg['volist'],$plusvolist);
            }
        }
        if ($plusvolist) {
            $this->wxpost['plusid'] = 1102;
            $this->Wxmsgadd($this->wxpost);
        }
    }


    public function checkSignature()
    {
        // return true;
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];    
        $token = md5($this->mid);
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
                
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }


    public function wxapi()
    {
    	$this->initindex();
        $Member = D('Member');
        $this->member = $Member->find($this->mid);
        if (!$this->member) return;
        if (!$this->Content && !$this->Event && !$this->MsgType) return;

        unset($map);
        $Mpaccount = M('Mpaccount');
        $map['mid'] = $this->mid;
        $this->mpaccount = $Mpaccount->where($map)->find();
        unset($map);


        //图文 关注回复
        if($this->Event == "subscribe"){
            unset($map);
            $map['mid'] = $this->mid;
            $map['iswelcome'] = array('eq',1);
            $News = D('News');
            $News->muser = $this->muser;
            $News->member = $this->member;
            $vos = $News->_list($map);
            if ($vos) {
                // $this->textdata['plusid'] = 101;
                // $this->Wxmsgadd($this->eventdata);
                $this->volist = $vos;
                $this->respon('news');
                return;
            }
        }

        //文本 关注回复
        if($this->Event == "subscribe"){
            unset($map);
            $map['mid'] = $this->mid;
            $map['msg'] = array('neq',' ');
            $map['iswelcome'] = array('eq',1);
            $Textinfo = M('Textinfo');
            $textinfo = $Textinfo->where($map)->find();
            if ($textinfo) {
                $Wxmsg = M('Wxmsg');
                $this->textdata['plusid'] = 101;
                $this->Wxmsgadd($this->wxpost);
                $this->msg = $textinfo['msg'];
                $this->respon('text');
                return;
            }
        }
        //文本 关注回复
        
        //退订信息
        if($this->Event == "unsubscribe"){
            unset($map);
            $map['mid'] = $this->mid;
            $map['msg'] = array('neq',' ');
            $Byemsg = M('Byemsg');
            $byemsg = $Byemsg->where($map)->find();
            if ($byemsg) {
                $Wxmsg = M('Wxmsg');
                $this->textdata['plusid'] = 102;
                $this->Wxmsgadd($this->eventdata);

                $this->initstrategy('unsubscribe');
                $this->acctioneCode = "SUCCESS";
                $this->addstrategy();

                // $this->msg = $byemsg['msg'];
                // $this->respon('text');
                // return;
            }
        }
        //退订信息


        //置顶查询  局部置顶
        $toplist = $this->topnews1();
        if ($toplist)  $this->volist = array_merge($this->volist,$toplist);

        //置底查询  局部置底
        $bottom1 = $this->bottomreply1();

        //微主页查询
        unset($map);
        $map['mid'] = $this->mid;
        $map['keyword'] = $this->Content;
        $Michome = D('Michome');
        $Michome->muser = $this->muser;
        $Michome->member = $this->member;
        $mic_vo = $Michome->wx_list($map);
        if ($mic_vo)  $this->volist[] = $mic_vo;
        //微主页查询


        

        //词库匹配
        $thesaurus = $this->matchTextInfo1();
        if ($thesaurus) {
            $Wxmsg = M('Wxmsg');
            $this->wxpost['plusid'] = 201;
            $this->Wxmsgadd($this->wxpost);
            $this->msg = $thesaurus['msg'];
            $this->respon('text');
            return;
        }
        $thesaurus = $this->matchTextInfo2();
        if ($thesaurus) {
            $Wxmsg = M('Wxmsg');
            $this->textdata['plusid'] = 202;
            $this->Wxmsgadd($this->textdata);
            $this->msg = $thesaurus['msg'];
            $this->respon('text');
            return;
        }
        $thesaurus = $this->matchTextInfo3();
        if ($thesaurus) {
            $Wxmsg = M('Wxmsg');
            $this->textdata['plusid'] = 203;
            $this->Wxmsgadd($this->textdata);
            $this->msg = $thesaurus['msg'];
            $this->respon('text');
            return;
        }
        $thesaurus = $this->matchTextInfo4();
        if ($thesaurus) {
            $Wxmsg = M('Wxmsg');
            $this->textdata['plusid'] = 204;
            $this->Wxmsgadd($this->textdata);
            $this->msg = $thesaurus['msg'];
            $this->respon('text');
            return;
        }
        
        //词库匹配



        $infolist = array();
        // $ilist = $this->matchNews1();
        // if ($ilist) {
        //     $this->textdata['plusid'] = 301;
        //     $this->Wxmsgadd($this->textdata);
        //     $infolist = array_merge($infolist,$ilist);
        // }

        $ilist = $this->matchNews2();
        if ($ilist && !$infolist) {
            $this->wxpost['plusid'] = 302;
            $this->Wxmsgadd($this->wxpost);
            $infolist = array_merge($infolist,$ilist);
        }
        $ilist = $this->matchNews3();
        if ($ilist && !$infolist) {
            $this->textdata['plusid'] = 303;
            $this->Wxmsgadd($this->textdata);
            $infolist = array_merge($infolist,$ilist);
        }
        $ilist = $this->matchNews4();
        if ($ilist && !$infolist) {
            $this->textdata['plusid'] = 304;
            $this->Wxmsgadd($this->textdata);
            $infolist = array_merge($infolist,$ilist);
        }
        //回复规则

        //插件查询
        $this->searchPlus();
        //插件查询

        //微主页分类查询
        $infoTypes = $this->itype();
        if ($infoTypes)  $this->volist = array_merge($this->volist,$infoTypes);
        //微主页分类查询

        //微主页文章查询
        $infos = $this->infos();
        if ($infos)  $this->volist = array_merge($this->volist,$infos);
        //微主页文章查询


        //置顶查询  全局置顶
        $toplist2 = $this->topnews2();
        if ($infolist)  $this->volist = array_merge($this->volist,$infolist);
        if ($toplist2 && $this->volist)  $this->volist = array_merge($toplist2,$this->volist);

        //置底查询 局部置底
        if ($bottom1 && $this->volist)  $this->volist = array_merge($this->volist,$bottom1);
        //置底查询 全局置底
        $bottom2 = $this->bottomreply2();
        if ($bottom2 && $this->volist)  $this->volist = array_merge($this->volist,$bottom2);


        if ($this->volist) {
            $this->respon('news');
            return;
        }


        //图文 自动回复
        unset($map);
        $map['mid'] = $this->mid;
        $map['ishelp'] = array('eq',1);
        $News = D('News');
        $News->muser = $this->muser;
        $News->member = $this->member;
        $vos = $News->_list($map);
        if ($vos && $this->FromUserName) {
            $this->wxpost['plusid'] = 1001;
            $this->Wxmsgadd($this->eventdata);
            $this->volist = $vos;
            $this->respon('news');
            return;
        }

        //文本 自动回复
        unset($map);
        $map['mid'] = $this->mid;
        $map['msg'] = array('neq',' ');
        $map['ishelp'] = array('eq',1);
        $Textinfo = M('Textinfo');
        $textinfo = $Textinfo->where($map)->find();
        if ($textinfo) {
            $Wxmsg = M('Wxmsg');
            $this->textdata['plusid'] = 1001;
            $this->Wxmsgadd($this->wxpost);
            $this->msg = $textinfo['msg'];
            $this->respon('text');
            return;
        }
        //文本 自动回复

    }
}